package com.qyer.search.threading;

import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

public abstract class AbstractThreadPoolHolder {

  private static final Logger LOGGER = LoggerFactory.getLogger(AbstractThreadPoolHolder.class);
  protected ExecutorService service;

  protected String name;

  public void destroy() throws InterruptedException {
    if (service == null) {
      LOGGER.info("Service({}) is null, nothing to do.", name);
      return;
    }
    int timeout = 5;
    TimeUnit tn = TimeUnit.SECONDS;
    LOGGER.info("Try shutdown thread-pool({})", name);
    service.shutdown();
    boolean normalFinished = false;
    try {
      normalFinished = service.awaitTermination(timeout, tn);
    } finally {
      if (normalFinished) {
        LOGGER
          .info("All threads of thread-pool({}) finished jobs in {} {} normally.", name, timeout,
                tn);
      } else {
        List<Runnable> droppedTasks = service.shutdownNow();
        int size = CollectionUtils.isEmpty(droppedTasks) ? 0 : droppedTasks.size();
        LOGGER.info("Some threads(total {}) of thread-pool({}) " +
                      "cannot finish their jobs in {} {}. Shutdown " +
                      "thread pool now.", name, size, timeout, tn);
      }
    }
  }

  public ExecutorService getService() {
    return this.service;
  }
}
